"""
有声读物服务模块
提供文本预处理、音频生成和进度跟踪功能
"""

# 导入必要的模块
from typing import List, Dict, Any, Optional
from ...models.audiobook import AudioBookChapter, AudioBookProgress
from ...core.logging import get_logger

from .processor import (
    TextPreprocessor,
    AudioBookProcessor,
    ChapterSegment,
    AudioBookStructure,
    audio_book_processor
)
from .generator import (
    AudioBookGenerator,
    GenerationRequest,
    GenerationTask,
    GenerationStatus,
    audio_book_generator,
    ChapterSegment
)
from .chapter_manager import (
    ChapterManager,
    ChapterOperation,
    ChapterOperation,
    chapter_manager
)
from .progress_tracker import (
    ProgressTracker,
    ProgressEvent,
    Bookmark,
    PlaybackSession,
    ProgressSnapshot,
    progress_tracker
)

__all__ = [
    # 文本处理
    'TextPreprocessor',
    'AudioBookProcessor',
    'ChapterSegment',
    'AudioBookStructure',
    'audio_book_processor',
    
    # 音频生成
    'AudioBookGenerator',
    'GenerationRequest',
    'GenerationTask',
    'GenerationStatus',
    'audio_book_generator',
    
    # 章节管理
    'ChapterManager',
    'ChapterOperation',
    'ChapterOperation',
    'chapter_manager',
    
    # 进度跟踪
    'ProgressTracker',
    'ProgressEvent',
    'Bookmark',
    'PlaybackSession',
    'ProgressSnapshot',
    'progress_tracker'
]

# 版本信息
__version__ = '1.0.0'
__author__ = 'Offline Language Player Team'


# 服务初始化
async def init_audiobook_services():
    """初始化有声读物服务"""
    try:
        # 初始化文本处理器
        await audio_book_processor.initialize()
        
        # 启动音频生成器
        await audio_book_generator.start()
        
        logger = get_logger(__name__)
        logger.info("Audio book services initialized successfully")
        return True
        
    except Exception as e:
        logger = get_logger(__name__)
        logger.error(f"Failed to initialize audio book services: {e}")
        return False


# 服务清理
async def cleanup_audiobook_services():
    """清理有声读物服务"""
    try:
        # 停止音频生成器
        await audio_book_generator.stop()
        
        logger = get_logger(__name__)
        logger.info("Audio book services cleaned up successfully")
        return True
        
    except Exception as e:
        logger = get_logger(__name__)
        logger.error(f"Failed to cleanup audio book services: {e}")
        return False


# 便捷函数
async def generate_audiobook(
    title: str,
    content: str,
    user_id: str,
    **kwargs
) -> str:
    """生成有声读物（便捷函数）"""
    request = GenerationRequest(
        title=title,
        content=content,
        user_id=user_id,
        **kwargs
    )
    
    return await audio_book_generator.submit_task(request)


async def get_audiobook_chapters(
    audiobook_id: str,
    user_id: str = None
) -> List[AudioBookChapter]:
    """获取有声读物章节（便捷函数）"""
    return await chapter_manager.get_chapters(audiobook_id, user_id)


async def update_reading_progress(
    user_id: str,
    audiobook_id: str,
    chapter_index: int,
    position: float,
    **kwargs
) -> Optional[AudioBookProgress]:
    """更新阅读进度（便捷函数）"""
    return await progress_tracker.update_progress(
        user_id=user_id,
        audiobook_id=audiobook_id,
        chapter_index=chapter_index,
        position=position,
        **kwargs
    )


async def start_playback(
    user_id: str,
    audiobook_id: str,
    chapter_index: int = None,
    position: float = None
) -> PlaybackSession:
    """开始播放（便捷函数）"""
    return await progress_tracker.start_playback(
        audiobook_id=audiobook_id,
        user_id=user_id,
        chapter_index=chapter_index,
        position=position
    )


async def pause_playback(
    user_id: str,
    audiobook_id: str
) -> Optional[AudioBookProgress]:
    """暂停播放（便捷函数）"""
    return await progress_tracker.pause_playback(user_id, audiobook_id)


async def get_user_reading_history(
    user_id: str,
    limit: int = 20
) -> List[Dict[str, Any]]:
    """获取用户阅读历史（便捷函数）"""
    return await progress_tracker.get_reading_history(user_id, limit)


async def add_bookmark(
    user_id: str,
    audiobook_id: str,
    chapter_index: int,
    position: float,
    title: str,
    description: str = ""
) -> Bookmark:
    """添加书签（便捷函数）"""
    return await progress_tracker.add_bookmark(
        user_id=user_id,
        audiobook_id=audiobook_id,
        chapter_index=chapter_index,
        position=position,
        title=title,
        description=description
    )


# 服务结束
